package com.example.portablefortheelderlybackground.config.redis;

import cn.hutool.core.util.IdUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;


public class redisLock {
    private final StringRedisTemplate stringRedisTemplate;
    private final String key;
    private static final String PRE_FIX = IdUtil.simpleUUID() + "-";

    //初始化
    public redisLock(String key, StringRedisTemplate redisTemplate) {
        this.key = key;
        this.stringRedisTemplate = redisTemplate;
    }

    //添加锁
    public boolean lock() {
        //这里的值可以先用uuid和线程id代替,这里单个uuid可以代表单个jvm,
        String value = PRE_FIX + Thread.currentThread().getId();
        //通过setIfAbsent方法进行上锁
        //同时添加时间,防止因线程崩溃,导致key锁无法被释放,时间一般选在10s左右
        return Boolean.TRUE.equals(this.stringRedisTemplate.opsForValue().setIfAbsent(key, value, 10, TimeUnit.SECONDS));
    }

    //释放锁
    public void unlock() {
        //获取锁的标识
        String value = PRE_FIX + Thread.currentThread().getId();
        //获取锁的值
        String keyValue = stringRedisTemplate.opsForValue().get(key);
        //判断keyValue是否相等
        if (!value.equals(keyValue)) {
            //如果不相等,则表明不是当前线程的锁,不进行对锁的释放
            return;
        }
        //释放锁
        this.stringRedisTemplate.delete(key);
    }
}
